package com.itheima.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClazzMapper clazzMapper;


    @Override
    public void violation(Integer id, Integer score) {
        // 扣分处理
        UpdateWrapper<Student> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id)
                .setSql("violation_score = violation_score + " + score)
                .setSql("violation_count = violation_count + 1" )
                .set("update_time", LocalDateTime.now());
        studentMapper.update(updateWrapper);
    }

    @Override
    public PageResult<Student> getConditionPageList(StudentQueryParam student) {
        Page<Student> studentPage = new Page<>(student.getPage(), student.getPageSize());
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        String name = student.getName();
        Integer degree = student.getDegree();
        Integer clazzId = student.getClazzId();
        queryWrapper.like(StrUtil.isNotEmpty(name), Student::getName, name)
                .eq(ObjUtil.isNotNull(degree), Student::getDegree, degree)
                .eq(ObjUtil.isNotNull(clazzId), Student::getClazzId, clazzId);
        this.page(studentPage, queryWrapper);
        List<Student> studentList = studentPage.getRecords();
        // 设置班级名称
        Map<Integer, String> clazzMaps = clazzMapper.selectList(null).stream().collect(Collectors.toMap(Clazz::getId, Clazz::getName));
        studentList.forEach(o -> o.setClazzName(clazzMaps.get(o.getClazzId())));
        return new PageResult<>(studentPage.getTotal(), studentList);
    }
}
